﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WinServiceKeepAlive
{
    public partial class Service1 : ServiceBase
    {
        LogHelper log = new LogHelper();

        /// <summary>
        /// ProjectInstaller 
        /// 要以本地系统方式安装 不然权限不够 LocalSystem 
        /// 普通执行数据任务的服务以本地服务方式安装 LocalService 即可
        /// </summary>
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            log.WriteLog("--------------------------服务启动--------------------------");
            Task t1 = Task.Factory.StartNew(SyncExecIntervalMinute);
        }

        protected override void OnStop()
        {
            log.WriteLog("--------------------------服务停止--------------------------");
        }

        /// <summary>
        /// 间隔执行（分）
        /// </summary>
        private void SyncExecIntervalMinute()
        {
            try
            {
                int intervalMinute = ConfigurationManager.AppSettings["IntervalMinute"].ToInt32();
                while (true)
                {
                    #region 执行业务代码

                    ExecIntervalMinuteFunc();

                    #endregion

                    Thread.Sleep(1000 * 60 * intervalMinute); //每分钟*intervalMinute
                }
            }
            catch (Exception ex)
            {
                log.WriteLog("异常：间隔执行（分）");
                log.WriteExceptionLog(ex);
            }
        }

        /// <summary>
        /// ExecIntervalMinuteFunc
        /// </summary>
        private void ExecIntervalMinuteFunc()
        {
            string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToString();
            if (string.IsNullOrEmpty(serviceName))
            {
                log.WriteLog("配置文件中没有指定服务名称！");
                return;
            }
            string[] serviceArray = serviceName.Split(',');
            List<string> serviceNameList = new List<string>(serviceArray);
            foreach (string serviceNameItem in serviceNameList)
            {
                try
                {
                    if (ServiceHelper.ISWindowsServiceInstalled(serviceNameItem))
                    {
                        if (!ServiceHelper.ISStart(serviceNameItem))
                        {
                            bool runStatus = ServiceHelper.StartService(serviceNameItem);
                            if (runStatus)
                            {
                                log.WriteLog($"服务 {serviceNameItem} 启动成功！");
                            }
                            else
                            {
                                log.WriteLog($"服务 {serviceNameItem} 启动失败！");
                            }
                        }
                    }
                    else
                    {
                        log.WriteLog($"服务 {serviceNameItem} 未安装！");
                    }
                }
                catch (Exception ex)
                {
                    log.WriteExceptionLog(ex);
                }
            }
        }
    }
}
